import {defineStore} from "pinia";
import {useMenuStore} from "~/store/modulers/menu";
import router from "~/router";
import {CommonApi} from "~/api/system/common.api";

const api = new CommonApi();
interface UserState {
    token?: string,
    user?: object,
}

export const useUserStore = defineStore("icesoft-user", {
    persist: {
        enabled: true,
    },
    state() {
        const state: UserState = {
            token: undefined,
            user: undefined,
        };
        return state;
    },
    actions: {
        setUserInfo(data: UserState) {
            window.localStorage.setItem("token", <string>data.token);
            this.token = data.token;
            this.user = data as any;
        },
        logout() {
            api.logout().then(resp=>{
                if (resp.ok) {
                    this.$reset();
                    useMenuStore().$reset();
                    window.localStorage.removeItem("token");
                    router.push("/login");
                }
            })
        },
    }
})
